<template>
  <div class="app-container">
    <div class="addzuhe">
      <el-button type="primary" plaiFn icon="el-icon-plus" size="mini" @click="handleAdd">新增组合</el-button>
    </div>
    <el-dialog title="量表组合" :visible.sync="dialogVisible" width="30%" center>
      <span>提示：为了确保测评结果的准确性，用户自定义添加的量表不支持组合分配！</span>
      <el-collapse v-model="activeName" accordion>
        <el-collapse-item v-for="(item, index) in dataArray" :title="item.scaleTitle" :name="item.scaleType"
          :key="index">
          <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div> -->
          <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="city in item.items" :label="city.scaleTitle" :key="city.scaletitle">{{ city.scaleTitle
              }}</el-checkbox>
          </el-checkbox-group>
        </el-collapse-item>
      </el-collapse>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveCombination">保存</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>

    <el-dialog title="量表组合" :visible.sync="dialogVisible1" width="30%" center>
      <span>提示：为了确保测评结果的准确性，用户自定义添加的量表不支持组合分配！</span>

      <el-collapse v-model="activeName" accordion>
        <el-collapse-item v-for="(item, index) in dataArray" :title="item.scaleTitle" :name="item.scaleType"
          :key="index">

          <!-- <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
            <div style="margin: 15px 0;"></div> -->
          <el-checkbox-group v-model="checkedCities" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="city in item.items" :label="city.scaleTitle" :key="city.scaletitle">{{ city.scaleTitle
              }}</el-checkbox>
          </el-checkbox-group>

        </el-collapse-item>
      </el-collapse>

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveCombination1" v-hasPermi="['system:combination:edit']">保存</el-button>
        <el-button @click="dialogVisible1 = false">取 消</el-button>
      </span>
    </el-dialog>

    <div class="biaoge">
      <el-table :data="tableCombinationData" style="width: 100%">
        <el-table-column width="70" align="center" />
        <el-table-column type="index" label="序号" width="120" align="center">
        </el-table-column>
        <el-table-column prop="combinationName" label="测试名称" width="360" align="center">
        </el-table-column>
        <el-table-column label="量表名称" width="120" align="center">
          <template slot-scope="scope">
            <div style="white-space: pre-line;">{{ scope.row.scaleTitle.join('\n') }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="scaleNum" label="量表个数" width="200" align="center">
        </el-table-column>
        <el-table-column label="操作" width="280" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="handleCheckedCitiesChange1(scope.row)"
              v-hasPermi="['system:combination:edit']">编辑组合</el-button>
            <el-button size="mini" type="text" @click="handUpdateCombination(scope.row)"
              v-hasPermi="['system:combination:editname']">修改组合</el-button>
            <el-button size="mini" type="text" @click="handDeleteCombination(scope.row)"
              v-hasPermi="['system:combination:remove']">删除组合</el-button>
            <el-button size="mini" type="text" @click="fenpeizuhe(scope.row)">分配组合</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { getScaleCombination, listScale, remove, updateCombinationName, addCombination, editCombination } from "@/api/mentalTest/combination";

export default {
  data () {
    return {
      dialogVisible1: false,
      rows: {},
      //复选框中选中元素的id
      checkedScaleIds: [],
      checkedScaleTitles: [],
      dialogValue1: "",
      // 选中数组
      ids: [],
      checkAll: false,
      checkedCities: [],
      isIndeterminate: true,

      dataArray: [],
      activeName: '1',
      //新增按钮点击确认后弹出的对话框
      dialogVisible: false,
      //查询量表组合数据
      tableCombinationData: [],
      //所有心理测评量表管理列表
      scaleList: {},
    };
  },
  created () {
    this.getScaleCombination();
    this.getList();
  },
  methods: {
    //添加字段
    getScaleTitle (scaleType) {
      switch (scaleType) {
        case "1":
          return "性格测评";
        case "2":
          return "个性测评";
        case "3":
          return "情商测评";
        case "4":
          return "职业测评";
        case "5":
          return "智力测评";
        case "6":
          return "焦虑测评";
        case "7":
          return "抑郁测评";
        default:
          return "";
      }
    },
    //新增组合按钮
    handleAdd () {
      this.$prompt('测试名称：', '新建组合', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.dialogVisible = true;
        this.dialogValue1 = value;
        this.$message({
          type: 'success',
          message: '新建组合: ' + value
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消新建'
        });
      });
    },
    //查询量表组合
    getScaleCombination () {
      getScaleCombination().then(res => {
        this.tableCombinationData = res.rows;
        console.log("res", this.tableCombinationData);
      })
    },
    /** 查询心理测评量表管理列表 */
    getList () {
      listScale().then(response => {
        // console.log("response", response);
        this.scaleList = response.rows;
        // console.log("所有心理测评量表管理列表", this.scaleList);
        const groupedData = this.scaleList.reduce((groups, item) => {
          const { scaleType } = item;
          if (groups[scaleType]) {
            groups[scaleType].push(item);
          } else {
            groups[scaleType] = [item];
          }
          return groups;
        }, {});
        this.dataArray = Object.entries(groupedData).map(([scaleType, items]) => ({ scaleType, items }))
        // console.log("123",groupedData);
        this.dataArray = this.dataArray.map(item => ({
          ...item,
          scaleTitle: this.getScaleTitle(item.scaleType)
        }))
        // console.log("456",this.dataArray);
      });
    },
    //全选
    // handleCheckAllChange(val) {
    //   if (val) {
    //     let allCities = [];
    //     this.dataArray.forEach(item => {
    //       allCities = allCities.concat(item.items.map(city => city.scaleTitle));
    //     });
    //     this.checkedCities = allCities;
    //   } else {
    //     this.checkedCities = [];
    //   }
    //   this.isIndeterminate = false;
    // },
    handleCheckedCitiesChange (value) {
      this.checkedScaleIds = []
      this.checkedScaleTitles = []
      let checkedCount = value.length;
      let allCities = [];
      this.dataArray.forEach(item => {
        allCities = allCities.concat(item.items.map(city => city.scaleTitle));
        item.items.forEach(city => {
          if (value.includes(city.scaleTitle)) {
            this.checkedScaleIds.push(city.scaleId);
            this.checkedScaleTitles.push(city.scaleTitle);
          }
        }
        );
      });
      this.checkAll = checkedCount === allCities.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < allCities.length;
      // console.log("选中的id",this.checkedScaleIds,this.checkedScaleTitles);
    },
    deleteGroup (id) {
      // console.log(id,)
      remove(id).then(res => {
        // console.log(res)
        if (res.code == 200) {
          this.getScaleCombination()

        } else {
          // this.$message.error('删除失败')
        }
      });
    },
    // 分配组合
    fenpeizuhe (row) {
      // console.log(row);
      this.$router.push({
        path: '/mentalTest/scaleSet/giveCombination',
        query: {
          row: row
        }
      })
    },
    //删除组合
    handDeleteCombination (row) {
      const scaleIds = row.id || this.ids;
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // console.log("123123")
        this.deleteGroup(scaleIds)

        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
      // console.log("row",row);        
      // const scaleIds = row.id || this.ids;
      // this.$modal.confirm('是否确认删除组合名称为"' + row.combinationName + '"的数据项？').then(function () {
      //   console.log("123123")
      //   remove(scaleIds).then(res=>{
      //     console.log(res)
      //     if(res.code == 200){
      //       this.getList()

      //       // this.$message.success('删除成功')
      //     }else{
      //       // this.$message.error('删除失败')
      //     }
      //    });
      // })
    },
    //修改组合
    handUpdateCombination (row) {
      // console.log("row",row);
      this.$prompt('修改名称', '组合名称', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        let data = {
          id: row.id,
          combinationName: value
        }
        updateCombinationName(data).then(res => {
          this.getScaleCombination();
        })

        // window.location.reload();
        this.$message({
          type: 'success',
          message: '修改后的组合名称是: ' + value
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });

    },
    //新增组合保存按钮
    saveCombination () {
      this.dialogVisible = false
      let data = {
        id: Date.now(),
        combinationName: this.dialogValue1,
        scaleId: this.checkedScaleIds
      }
      addCombination(data).then(res => {
        this.getScaleCombination();

      })
    },
    //编辑组合保存按钮
    saveCombination1 () {
      this.dialogVisible1 = false
      let data = {
        id: this.rows.id,
        combinationName: this.rows.combinationName,
        scaleId: this.checkedScaleIds
      }
      // console.log("data", data);
      editCombination(data).then(res => {
        this.getScaleCombination();

      })
    },
    //编辑组合
    handleCheckedCitiesChange1 (row) {
      this.rows = row
      // console.log("rows", this.rows);
      this.dialogVisible1 = true;
    }
  }
};
</script>
<style>
.addzuhe {
  margin-bottom: 20px;
  margin-left: 20px;
}

.biaoge {
  margin-left: 20px;
}
</style>